package com.osdp.common.sercurity.service.impl;

import com.osdp.common.sercurity.domain.Principal;
import com.osdp.common.sercurity.service.IAuthenticateService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 默认实现
 *
 * UsernamePasswordAuthenticationToken继承AbstractAuthenticationToken实现Authentication
 * 所以当在页面中输入用户名和密码之后首先会进入到UsernamePasswordAuthenticationToken验证(Authentication)，
 * 然后生成的Authentication会被交由AuthenticationManager来进行管理
 * 而AuthenticationManager管理一系列的AuthenticationProvider，
 * 而每一个Provider都会通UserDetailsService和UserDetail来返回一个
 * 以UsernamePasswordAuthenticationToken实现的带用户名和密码以及权限的Authentication
 */
public abstract class DefaultAuthenticateService implements IAuthenticateService {

    public UsernamePasswordAuthenticationToken createUsernamePasswordAuthenticationToken(Principal principal){
        Collection<String> roleCodes = getRoleCodes(principal.getPrincipalId());
        List<SimpleGrantedAuthority> authorities = Lists.newArrayList();
        if(!CollectionUtils.isEmpty(roleCodes)){
            authorities = roleCodes.stream().map(e->new SimpleGrantedAuthority(String.format("ROLE_%",e))).collect(Collectors.toList());
        }
        Collection<String> permissionCodes = getPermissionCodes(principal.getPrincipalId());
        if(!CollectionUtils.isEmpty(permissionCodes)){
            List<SimpleGrantedAuthority> permissions = permissionCodes.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
            authorities.addAll(permissions);
        }
        return new UsernamePasswordAuthenticationToken(principal, null, authorities);
    }
}
